﻿/*-----------------------------------------------
// File: UltimateSkill.cs
// Description: 
// Author: Shaobing	492057342@qq.com
-----------------------------------------------*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Battle.View
{
    public class UltimateSkill : BattleSkill
    {
        public string ultiResourceName;
        public string ultiPaintResUrl;
        public enum UltimateCameraEndType
        {
            FocusEnemy,
            FocusMine,
            All
        }
        public string ultimateReadyAudio;
        public string ultimateEndHitAudio;

        public UltimateCameraEndType cameraEndType;

        public string changeLeftWeaponId;
        public string changeRightWeaponId;

        public ParticleData ultiFinalBeHitParticleData;
        public ParticleData ultiFInalBeHitOwnParticleData;

        public List<UltimateSkillFaceChangeInfo> faceChangeInfo = new List<UltimateSkillFaceChangeInfo>();
        public Dictionary<string, UltimatePositionSpecialDealInfo> speDealInfo = new Dictionary<string, UltimatePositionSpecialDealInfo>();

        public UltimateSkill(BattleActorSkillData data, BattleCharacter _bc) : base(data, _bc)
        {
            var dict = Dict.Blo.DictHeroSkillBlo.GetTableUltimateSkill(HSId);
            ultiResourceName = dict.EffectResourceName;
            ultiPaintResUrl = dict.PaintResUrl;
            if (!string.IsNullOrEmpty(dict.FinalBeHitEffect))
            {
                ultiFinalBeHitParticleData = ParticleData.CreateParticleData(dict.FinalBeHitEffect, dict.FinalBeHitEffectBone);
            }
            if (!string.IsNullOrEmpty(dict.FinalBeHitOwnEffect)) {
                ultiFInalBeHitOwnParticleData = ParticleData.CreateParticleData(dict.FinalBeHitOwnEffect, dict.FinalBeHitOwnEffectBone);
            }
            if (dict.IsFinalCameraRun == 0)
            {
                cameraEndType = UltimateCameraEndType.FocusMine;
            }
            else if (dict.IsFinalCameraRun == 1)
            {
                cameraEndType = UltimateCameraEndType.FocusEnemy;
            }
            else
            {
                cameraEndType = UltimateCameraEndType.All;
            }
            changeLeftWeaponId = dict.ChangeLeftWeaponResName;
            changeRightWeaponId = dict.ChangeRightWeaponResName;
            faceChangeInfo = ParseUltimateFaceChangeInfo(dict.ChangeFaceInfo);
            speDealInfo = ParseUltimatePositionSpecialDealInfo(dict.PositionSpecialDeal);
            ultimateReadyAudio = dict.UltiAudio;
            ultimateEndHitAudio = dict.UltiHitAudio;

        }


        public override IEnumerator LoadResource()
        {
            //System.DateTime dt = System.DateTime.Now;
            int taskCount = 0;
            foreach (var effectData in effectDatas)
            {
                ParticleFactory.RegistParticle(effectData.resUrl, () => { taskCount--; });
                taskCount++;
            }
            foreach (var release in releases)
            {
                BattleViewCtrl.GetInstance().StartCoroutine(release.LoadResource());
            }
            if (!string.IsNullOrEmpty(skillAudio))
            {
                BattleViewCtrl.GetInstance().StartCoroutine(
                    AudioManager.Instance.LoadAudioResource(skillAudio, () => { taskCount--; })
                    );
                taskCount++;
            }
            if (!BattleViewCtrl.GetInstance().IsHaveUltimateLogic(HSId))
            {
                AssetLoadHelper.Instance.LoadAssetAsync("ultimate/" + ultiResourceName, ultiResourceName,typeof(GameObject), (obj) =>
                    {
                        GameObject go = obj as GameObject;
                        if (go != null)
                        {
                            go.SetActive(false);
                            BattleViewCtrl.GetInstance().AddUltimateLogic(HSId, go.GetComponent<UltimateLogic>());
                        }
                        taskCount--;
                    });
                taskCount++;
            }
            else
            {
                var logic = BattleViewCtrl.GetInstance().GetUltimateLogic(HSId);
                BattleViewCtrl.GetInstance().AddUltimateLogic(HSId, logic);
            }
            if (ultiFinalBeHitParticleData != null)
            {
                ParticleFactory.RegistParticle(ultiFinalBeHitParticleData.resUrl, () => { taskCount--; });
                taskCount++;
            }
            if (ultiFInalBeHitOwnParticleData != null) {
                ParticleFactory.RegistParticle(ultiFInalBeHitOwnParticleData.resUrl, () => { taskCount--; });
                taskCount++;
            }

            if (!string.IsNullOrEmpty(ultiPaintResUrl))
            {
#if !FIX_RESOURCE
                yield return BattleViewCtrl.GetInstance().StartCoroutine(AssetLoad.AssetBundleManager.Instance.LoadAssetBundleCoroutine(ultiPaintResUrl));
                AssetLoad.AssetBundleManager.Instance.GetAssetFromBundle(ultiPaintResUrl, CommonMethod.GetAssetNameFromAssetBundleName(ultiPaintResUrl), typeof(GameObject));
#else
                AssetLoad.ResourceManager.Instance.LoadResource(ultiPaintResUrl);
#endif
            }

            if (!string.IsNullOrEmpty(ultimateReadyAudio))
            {
                BattleViewCtrl.GetInstance().StartCoroutine(
                AudioManager.Instance.LoadAudioResource(ultimateReadyAudio, () =>
                {
                    taskCount--;
                }));
                taskCount++;
            }

            if (!string.IsNullOrEmpty(ultimateEndHitAudio))
            {
                BattleViewCtrl.GetInstance().StartCoroutine(
                    AudioManager.Instance.LoadAudioResource(ultimateEndHitAudio, () => { taskCount--; })
                    );
                taskCount++;
            }

            while (taskCount > 0)
            {
                yield return null;
            }

            while (!IsReleaseLoadComplete())
            {
                yield return null;
            }
            //Debug.Log("Load ultimate skill " + GetOwnBC().heroName + " " + HSId + " cost time: " + (System.DateTime.Now - dt).TotalMilliseconds);
            isLoadComplete = true;
        }

        public override void UnloadResource()
        {
            base.UnloadResource();
            BattleViewCtrl.GetInstance().RemoveUltimateLogic(HSId, ultiResourceName);

            if (!string.IsNullOrEmpty(ultiPaintResUrl))
            {
#if !FIX_RESOURCE
                AssetLoad.AssetBundleManager.Instance.UnloadAssetBundle(ultiPaintResUrl);
#else
                AssetLoad.ResourceManager.Instance.UnloadResource(ultiPaintResUrl);
#endif
            }

            if (!string.IsNullOrEmpty(ultimateReadyAudio))
            {
                AudioManager.Instance.UnloadAudioResource(ultimateReadyAudio);
            }

            if (!string.IsNullOrEmpty(ultimateEndHitAudio))
            {
                AudioManager.Instance.UnloadAudioResource(ultimateEndHitAudio);
            }

            if (ultiFInalBeHitOwnParticleData != null) {
                ParticleFactory.UnRegistParticle(ultiFInalBeHitOwnParticleData.resUrl);
            }
            if (ultiFinalBeHitParticleData != null) {
                ParticleFactory.UnRegistParticle(ultiFinalBeHitParticleData.resUrl);
            }
        }

        public UltimateLogic GetUltimateLogic()
        {
            return BattleViewCtrl.GetInstance().GetUltimateLogic(HSId);
        }
        public UltimateData GetUltimateData()
        {
            return GetUltimateLogic().GetComponent<UltimateData>();
        }

        public override bool IsSkillCanCast()
        {
            return !IsCasted && isCanCast && BattleViewCtrl.GetInstance().GetAngerNum(bc.camp) >= Dict.Blo.DictConfigBlo.GetUltimateCostAngerNum();
        }
        public override bool IsSkillCanCast4UI()
        {
            return !IsPressed && isCanCast && BattleViewCtrl.GetInstance().GetAngerNum(bc.camp) >= Dict.Blo.DictConfigBlo.GetUltimateCostAngerNum();
        }

        public bool isChangeWeapon()
        {
            return !string.IsNullOrEmpty(changeLeftWeaponId) || !string.IsNullOrEmpty(changeRightWeaponId);
        }

        public Dictionary<string, UltimatePositionSpecialDealInfo> ParseUltimatePositionSpecialDealInfo(string info)
        {
            Dictionary<string, UltimatePositionSpecialDealInfo> res = new Dictionary<string, UltimatePositionSpecialDealInfo>();
            var arr = info.Split(new char[1] { '#' }, System.StringSplitOptions.RemoveEmptyEntries);
            foreach (var arr0 in arr)
            {
                var arr1 = arr0.Split(new char[1] { ':' }, System.StringSplitOptions.RemoveEmptyEntries);
                if (arr1.Length == 3)
                {
                    string heroId = arr1[0];
                    float scale = float.Parse(arr1[1]);
                    Vector3 offset = TableConvertUtil.String2Vector3(arr1[2]);
                    UltimatePositionSpecialDealInfo dealInfo = new UltimatePositionSpecialDealInfo(heroId, scale, offset);
                    if (res.ContainsKey(dealInfo.specialHeroId))
                    {
                        Debug.LogError("[UltimateSkill] Have Repeated HeroId :" + heroId + " Skill:" + HSId);
                    }
                    else
                    {
                        res.Add(dealInfo.specialHeroId, dealInfo);
                    }
                }
            }
            return res;
        }

        public List<UltimateSkillFaceChangeInfo> ParseUltimateFaceChangeInfo(string info)
        {
            List<UltimateSkillFaceChangeInfo> res = new List<UltimateSkillFaceChangeInfo>();
            var arr = info.Split(new char[1] { '#' }, System.StringSplitOptions.RemoveEmptyEntries);
            foreach (var arr0 in arr)
            {
                var arr1 = arr0.Split(new char[1] { '=' }, System.StringSplitOptions.RemoveEmptyEntries);
                if (arr1.Length == 2)
                {
                    string faceId = arr1[1];
                    var arr2 = arr1[0].Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
                    if (arr2.Length == 2)
                    {
                        float startTime;
                        float stopTime;
                        if (!float.TryParse(arr2[0], out startTime))
                        {
                            continue;
                        }
                        if (!float.TryParse(arr2[1], out stopTime))
                        {
                            continue;
                        }

                        UltimateSkillFaceChangeInfo changeInfo = new UltimateSkillFaceChangeInfo(startTime, stopTime, faceId);
                        res.Add(changeInfo);
                    }
                }
            }
            return res;
        }


        public override void Enqueue()
        {
            base.Enqueue();
            BattleManager.Instance.battlePanel.UltimateHide();
        }

    }


    public class UltimateSkillFaceChangeInfo
    {
        public float startTime;
        public float stopTime;
        public string faceId;

        public UltimateSkillFaceChangeInfo(float startTime, float stopTime, string faceId)
        {
            this.startTime = startTime;
            this.stopTime = stopTime;
            this.faceId = faceId;
        }
    }

    public class UltimatePositionSpecialDealInfo
    {
        public string specialHeroId;
        public float scale;
        public Vector3 offset;
        public UltimatePositionSpecialDealInfo(string heroId, float _scale, Vector3 _offset)
        {
            this.specialHeroId = heroId;
            this.scale = _scale;
            this.offset = _offset;
        }
    }

}
